import json
import aiohttp
import os


module_src = os.path.abspath(__file__)
module_dir = os.path.dirname(module_src)

BANKEND_DOMAIN = "https://supplier.casmart.com.cn"


class AsyncSessionManager:

    def __init__(self):
        self.session = None

    async def start(self):
        """启动session"""
        if self.session is None:
            # 设置连接数
            connector = aiohttp.TCPConnector(
                limit=100,  # 总连接池大小
                limit_per_host=5,  # 每个主机的连接数
                keepalive_timeout=30,
                enable_cleanup_closed=True,
                ssl=False,
            )

            # 设置超时时间
            timeout = aiohttp.ClientTimeout(
                total=60, connect=5, sock_read=10  # 总超时时间  # 连接超时  # 读取超时
            )

            # 设置请求请求头
            headers = {
                "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36",
                "Referer": "https://supplier.casmart.com.cn",
            }

            # 创建 session 实例
            self.session = aiohttp.ClientSession(
                connector=connector, timeout=timeout, headers=headers
            )

    async def close(self):
        """关闭session"""
        if self.session is not None:
            await self.session.close()
            self.session = None

    async def get_captcha(self):
        """获取验证码"""
        VERYFY_URL = "https://sso.casmart.com.cn/verify-code"
        async with self.session.get(url=VERYFY_URL) as response:
            if response.status == 200:
                return await response.content.read()

            else:
                raise Exception(f"❌获取验证码失败: {response.status}")

    async def get_client_key(self, verify_code: str):
        LOGIN_URL = "https://sso.casmart.com.cn/login?channel-id=1&return-url=http://supplier.casmart.com.cn/"
        heardes = {  # 请求头
            "Origin": "https://sso.casmart.com.cn/",
            "content-type": "application/json",
        }
        user_data = {  # 登录参数
            "channelId": "1",
            "returnUrl": "http://supplier.casmart.com.cn/",
            "userName": "1757236480@qq.com",
            "password": "A123456789a",
            "verifycode": verify_code,
        }

        async with self.session.post(
            url=LOGIN_URL, headers=heardes, data=json.dumps(user_data)
        ) as response:
            if response.status == 200:
                res = await response.json()
                if res["success"] == True:
                    return res["data"]["clientKey"]
                else:
                    raise Exception(f"❌获取 clientKey 失败: {res['msg']}")
            else:
                raise Exception(f"❌发起登录请求失败: {response.status}")

    async def get_login_cookie(self, client_key):
        REDIRECT_URL = "https://sso.casmart.com.cn/redirect"

        data = {
            "returnUrl": "http://supplier.casmart.com.cn/",
            "channelId": "1",
            "clientKey": client_key,
        }

        async with self.session.post(url=REDIRECT_URL, data=data) as response:
            if response.status == 200:
                print("======= 获取 cookie =======")
                print("✅登录成功")
            else:
                raise Exception(f"❌验证码错误: {response.status}")

    async def supplier_stationid(self):
        url = f"{BANKEND_DOMAIN}/index/firstSupplierStationId"
        async with self.session.get(url=url) as response:
            if response.status == 200:
                print("✅获取 firstSupplierStationId 成功")
            else:
                raise Exception(
                    f"❌获取 firstSupplierStationId 失败: {response.status}"
                )


class AsyncRequestHanlder(AsyncSessionManager):
    def __init__(self):
        super().__init__()

    async def upload_product(self, pro_data: dict):
        """异步上传商品方法

        Args:
            pro_data (dict): 商品数据

        Returns:
            dict: 返回结果
        """
        url = f"{BANKEND_DOMAIN}/product/basic/save"
        data = json.dumps(pro_data, separators=(",", ":"))
        headers = {
            "Referer": "https://supplier.casmart.com.cn/product/basic/add",
            "Content-Type": "application/json",
        }
        self.session.headers.update(headers)

        async with self.session.post(url=url, data=data) as response:
            return await response.json()

    async def get_product_list(self):
        """获取商品列表"""
        url = f"{BANKEND_DOMAIN}/product/basic/list"
        data = {
            "page": 1,
            "count": 10,
            "params": {
                "brandName": "",
                "cateId": "",
                "tabIndex": "1",
                "stationId": "",
                "brandId": "5693",
                "deliveryId": "",
                "searchType": "0",
                "search": "",
            },
        }
        data = json.dumps(data, separators=(",", ":"))
        async with self.session.get(url=url, data=data) as response:
            return await response.json()
